package com.xiaochao.bigdata.util
import scala.util.control.Breaks._

/**
  * 字符串工具类
  * @author Administrator
  *
  */
object StringUtils {

  /**
    * 判断字符串是否为空
    *
    * @param str 字符串
    * @return 是否为空
    */
  def isEmpty(str: String): Boolean = str == null || "" == str

  /**
    * 判断字符串是否不为空
    *
    * @param str 字符串
    * @return 是否不为空
    */
  def isNotEmpty(str: String): Boolean = str != null && !("" == str)

  /**
    * 截断字符串两侧的逗号
    *
    * @param str 字符串
    * @return 字符串
    */
  def trimComma(str: String): String = {

    var subStr:Any = if (str.startsWith(",")) {

      val str2 = str.substring(1)

      str2
    }

    subStr = if (str.endsWith(",")) str.substring(0,str.length-1)


    if ((subStr + "").length > 0) subStr+""
    else
      str

  }

  /**
    * 补全两位数字
    *
    * @param str
    * @return
    */
  def fulfuill(str: String): String = if (str.length == 2) str
  else "0" + str

  /**
    * 从拼接的字符串中提取字段
    *
    * @param str       字符串
    * @param delimiter 分隔符
    * @param field     字段
    * @return 字段值
    */
  def getFieldFromConcatString(str: String, delimiter: String, field: String): String = {
    val fields = str.split(delimiter)
    for (concatField <- fields) {
      val fieldName = concatField.split("=")(0)
      val fieldValue = concatField.split("=")(1)
      if (fieldName == field) return fieldValue
    }
    null
  }

  /**
    * 从拼接的字符串中给字段设置值
    *
    * @param str           字符串
    * @param delimiter     分隔符
    * @param field         字段名
    * @param newFieldValue 新的field值
    * @return 字段值
    */
  def setFieldInConcatString(str: String, delimiter: String, field: String, newFieldValue: String): String = {
    val fields = str.split(delimiter)

    val buffer = new StringBuffer("")
    for (item <- fields) {
      val fieldName = item.split("=")(0)
      if (fieldName == field) {
        val concatField = fieldName + "=" + newFieldValue
        buffer.append(concatField).append("|")
      } else {
        buffer.append(item).append("|")
      }
    }
    buffer.substring(0, buffer.length() - 1)
  }

}
